<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\Complain as ComplainModel;
use app\payment\model\PaymentPayCompany as PaymentPayCompanyModel;
use app\payment\model\Download as DownloadModel;
use think\facade\Env;
use think\facade\Request;
use think\Db;

/**
 * 投诉控制器
 */
class Complain extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if (!in_array(request()->action(), ['index', 'see', 'export'])) {
            if ($this->no_auth) {
                $this->error('权限不足！');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 获取查询条件
        $map = $this->getMap();

        $list_rows = input('list_rows', 20) >= 20 ? 20 : input('list_rows');
        // 数据列表
        $data_list = ComplainModel::where($map)->order('create_time desc')->paginate($list_rows);

        // 分页数据
        $page = $data_list->render();

        $date = date('Y-m-d');
        $search = [
            ['daterange:6', 'create_time', '创建时间', '', "$date 00:00:00 - $date 23:59:59", ['max-date' => "$date 23:59:59", 'format' => 'YYYY-MM-DD HH:mm:ss', 'time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ['select:3', 'type', '类型', '', '', ['投诉列表', '投诉订单号']],
        ];

        $items = [
            ['id', 'ID'],
            ['order_id', '订单号'],
            ['child_company_name', '名称'],
            ['child_company_title', '标题'],
            ['status', '状态', 'status', '', ['失败', '成功']],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['right_button', '操作', 'btn']
        ];

        $export = [
            'title' => '导出',
            'icon' => 'fa fa-fw fa-arrow-circle-o-down',
            'target' => '_blank',
            'class' => 'btn btn-xs btn-default',
            'href' => url('export', ['map' => json_encode($map)]),
            'data-title' => '真的要导出吗？',
            'data-tips' => '导出可能要点时间,请再次点击导出',
        ];

        // 处理订单
        $handle = [
            'title' => '处理订单',
            'icon' => 'fa fa-fw fa-battery-4',
            'class' => 'btn btn-success',
            'href' => url('handle')
        ];

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('投诉列表') // 设置页面标题
            ->setTableName('Complain') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->hideCheckbox()
            ->addColumns($items)
            ->addTopButtons('add') // 批量添加顶部按钮
            ->addTopButton('handle', $handle) // 添加按钮
            ->addTopButton('export', $export) // 添加按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->setSearchArea($search) // 设置搜索区域  
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (empty($data['child_company'])) {
                $this->error('请选择支付公司！');
            }
            $pay_config = PaymentPayCompanyModel::where(['name' => $data['child_company']])->find();

            // 支付宝
            if ($data['class'] == 0) {
                // 投诉列表
                if ($data['type'] == 0) {
                    include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
                    include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayMerchantTradecomplainBatchqueryRequest.php';

                    // $arr['target_infos']['target_id'] = $pay_config['app_id'];    // 应用id，例如小程序id
                    // $arr['target_infos']['target_type'] = 'PUBLICID';             // 应用类型 小程序传入：APPID 生活号传入：PUBLICID
                    /*
                    投诉工单状态
                    商家处理中：MERCHANT_PROCESSING
                    商家已反馈：MERCHANT_FEEDBACKED
                    投诉已完结：FINISHED
                    投诉已撤销：CANCELLED
                    平台处理中：PLATFORM_PROCESSING
                    平台处理完结：PLATFORM_FINISH
                    系统关闭：CLOSED
                    */
                    // $arr['status'] = $data['status'];                          // 投诉工单状态
                    $arr['begin_time'] = $data['begin_time'];                     // 查询开始时间
                    $arr['end_time'] = $data['end_time'];                         // 查询结束时间
                    $arr['page_size'] = $data['page_size'];                       // 每页条数，默认10条，最多支持20条
                    $arr['page_num'] = $data['page_num'] + 1;                     // 当前页，从1开始

                    $aop = new \AopClient();
                    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                    $aop->appId = $pay_config['app_id'];
                    $aop->rsaPrivateKey = $pay_config['key'];
                    $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
                    $aop->apiVersion = '1.0';
                    $aop->signType = 'RSA2';
                    $aop->postCharset = 'utf-8';
                    $aop->format = 'json';

                    // 查询交易投诉列表
                    $request = new \AlipayMerchantTradecomplainBatchqueryRequest();
                    $request->setBizContent(json_encode($arr));
                    $result = $aop->execute($request);
                    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                    $resultCode = $result->$responseNode->code;
                    if (!empty($resultCode) && $resultCode == 10000) {
                        $datas['status'] = 1;
                    } else {
                        $datas['status'] = 0;
                    }
                    $datas['order_id'] = '';
                    $datas['type'] = 0;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = json_encode($result->$responseNode);
                    $datas['create_time'] = time();
                }

                // 投诉订单号
                if ($data['type'] == 1) {
                    include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
                    include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayMerchantTradecomplainQueryRequest.php';

                    $arr['complain_event_id'] = $data['order_id'];                         // 支付宝侧投诉单号

                    $aop = new \AopClient();
                    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                    $aop->appId = $pay_config['app_id'];
                    $aop->rsaPrivateKey = $pay_config['key'];
                    $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
                    $aop->apiVersion = '1.0';
                    $aop->signType = 'RSA2';
                    $aop->postCharset = 'utf-8';
                    $aop->format = 'json';

                    // 查询交易投诉列表
                    $request = new \AlipayMerchantTradecomplainQueryRequest();
                    $request->setBizContent(json_encode($arr));
                    $result = $aop->execute($request);
                    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                    $resultCode = $result->$responseNode->code;
                    if (!empty($resultCode) && $resultCode == 10000) {
                        $datas['status'] = 1;
                    } else {
                        $datas['status'] = 0;
                    }
                    $datas['order_id'] = $data['order_id'];
                    $datas['type'] = 1;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = json_encode($result->$responseNode);
                    $datas['create_time'] = time();
                }
            }

            // 微信
            if ($data['class'] == 1) {
                // 投诉列表
                if ($data['type'] == 0) {
                    $arr['limit'] = $data['page_size'];                                    // 分页大小
                    $arr['offset'] = $data['page_num'];                                    // 分页开始位置
                    $arr['begin_date'] = date("Y-m-d", strtotime($data['begin_time']));    // 开始日期
                    $arr['end_date'] = date("Y-m-d", strtotime($data['end_time']));        // 结束日期
                    //$arr['complainted_mchid'] = $pay_config['merchant_id'];                // 被诉商户号             

                    $url_path = http_build_query($arr);
                    //$url_path = "limit={$arr['limit']}&offset={$arr['offset']}&begin_date={$arr['begin_date']}&end_date={$arr['end_date']}&complainted_mchid={$arr['complainted_mchid']}";
                    $url = 'https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2?' . $url_path;

                    $mchid = $pay_config['merchant_id'];
                    $serial_no = $pay_config['other_public_key'];
                    $key = $pay_config['other_three'];
                    $temp = chunk_split($key, 64, "\n");
                    $key = "-----BEGIN PRIVATE KEY-----\n$temp-----END PRIVATE KEY-----\n";
                    $mch_private_key = openssl_get_privatekey($key);  // 私钥 
                    $timestamp = time();  // 时间戳
                    $nonce = md5($timestamp);  // 随机串
                    $http_method = 'GET';

                    $body = '';

                    $url_parts = parse_url($url);
                    $canonical_url = $url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : "");
                    $message = $http_method . "\n" .
                        $canonical_url . "\n" .
                        $timestamp . "\n" .
                        $nonce . "\n" .
                        $body . "\n";

                    openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
                    $sign = base64_encode($raw_sign);

                    $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $serial_no, $sign);

                    $header = [
                        'Accept: application/json',
                        'User-Agent: */*',
                        'Content-Type: application/json; charset=utf-8',
                        'Authorization: ' . $token,
                    ];

                    /*
                    PENDING：待处理
                    PROCESSING：处理中
                    PROCESSED：已处理完成
                    */

                    $resdata = go_curl($url, '', 'get', $pay_config['wait_second'], $header);
                    if (!empty($resdata)) {
                        $datas['status'] = 1;
                    } else {
                        $datas['status'] = 0;
                    }
                    $datas['order_id'] = '';
                    $datas['type'] = 0;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = $resdata;
                    $datas['create_time'] = time();
                }

                // 投诉订单号
                if ($data['type'] == 1) {
                    $arr['limit'] = $data['page_size'];                                    // 分页大小
                    $arr['offset'] = $data['page_num'];                                    // 分页开始位置
                    $arr['begin_date'] = date("Y-m-d", strtotime($data['begin_time']));    // 开始日期
                    $arr['end_date'] = date("Y-m-d", strtotime($data['end_time']));        // 结束日期
                    $arr['complainted_mchid'] = $pay_config['merchant_id'];                // 被诉商户号             

                    $url_path = $data['order_id'];
                    $url = 'https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/' . $url_path;

                    $mchid = $pay_config['merchant_id'];
                    $serial_no = $pay_config['other_public_key'];
                    $key = $pay_config['other_three'];
                    $temp = chunk_split($key, 64, "\n");
                    $key = "-----BEGIN PRIVATE KEY-----\n$temp-----END PRIVATE KEY-----\n";
                    $mch_private_key = openssl_get_privatekey($key);  // 私钥 
                    $timestamp = time();  // 时间戳
                    $nonce = md5($timestamp);  // 随机串
                    $http_method = 'GET';

                    $body = '';

                    $url_parts = parse_url($url);
                    $canonical_url = $url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : "");
                    $message = $http_method . "\n" .
                        $canonical_url . "\n" .
                        $timestamp . "\n" .
                        $nonce . "\n" .
                        $body . "\n";

                    openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
                    $sign = base64_encode($raw_sign);

                    $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $serial_no, $sign);

                    $header = [
                        'Accept: application/json',
                        'User-Agent: */*',
                        'Content-Type: application/json; charset=utf-8',
                        'Authorization: ' . $token,
                    ];

                    /*
                    PENDING：待处理
                    PROCESSING：处理中
                    PROCESSED：已处理完成
                    */

                    $resdata = go_curl($url, '', 'get', $pay_config['wait_second'], $header);
                    if (!empty($resdata)) {
                        $datas['status'] = 1;
                    } else {
                        $datas['status'] = 0;
                    }
                    $datas['order_id'] = $data['order_id'];
                    $datas['type'] = 1;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = $resdata;
                    $datas['create_time'] = time();
                }
            }

            if (ComplainModel::create($datas)) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }

        // 支付公司    
        $payment_company = PaymentPayCompanyModel::where(['status' => 1])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $start_time = date("Y-m-d", time() - 86400 * 7);
        $end_time = date("Y-m-d") . ' 23:59:59';

        $items = [
            ['radio', 'class', '方式', '', ['支付宝', '微信'], 0],
            ['radio', 'type', '类型', '', ['投诉列表', '投诉订单号'], 0],
            ['select', 'child_company', '支付公司', '', $payment_company],
            ['text', 'order_id', '投诉订单号'],
            ['datetime', 'begin_time', '开始日期', '', $start_time, 'YYYY-MM-DD HH:mm:ss'],
            ['datetime', 'end_time', '结束日期', '', $end_time, 'YYYY-MM-DD HH:mm:ss'],
            ['text', 'page_num', '当前页', '', 0],
            ['text', 'page_size', '每页条数', '', 20],
            ['text', 'status', '投诉工单状态', '',],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('投诉') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 处理订单
     * @return mixed
     */
    public function handle()
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            if (empty($data['child_company'])) {
                $this->error('请选择支付公司！');
            }
            $pay_config = PaymentPayCompanyModel::where(['name' => $data['child_company']])->find();

            // 支付宝
            if ($data['class'] == 0) {
                // 回复用户
                if ($data['type'] == 0) {
                    include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
                    include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayMerchantTradecomplainReplySubmitRequest.php';

                    $arr['complain_event_id'] = $data['order_id'];        // 支付宝侧投诉单号
                    $arr['reply_content'] = $data['remark'];              // 回复内容 

                    $aop = new \AopClient();
                    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                    $aop->appId = $pay_config['app_id'];
                    $aop->rsaPrivateKey = $pay_config['key'];
                    $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
                    $aop->apiVersion = '1.0';
                    $aop->signType = 'RSA2';
                    $aop->postCharset = 'utf-8';
                    $aop->format = 'json';

                    // 查询交易投诉列表
                    $request = new \AlipayMerchantTradecomplainReplySubmitRequest();
                    $request->setBizContent(json_encode($arr));
                    $result = $aop->execute($request);
                    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                    $resultCode = $result->$responseNode->code;
                    if (!empty($resultCode) && $resultCode == 10000) {
                        $datas['status'] = 1;
                    } else {
                        $datas['status'] = 0;
                    }
                    $datas['order_id'] = $data['order_id'];
                    $datas['type'] = 0;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = $resdata;
                    $datas['create_time'] = time();
                }

                // 处理完成
                if ($data['type'] == 1) {
                    include_once Env::get('extend_path') . 'alipaySdk/aop/AopClient.php';
                    include_once Env::get('extend_path') . 'alipaySdk/aop/request/AlipayMerchantTradecomplainFeedbackSubmitRequest.php';

                    $arr['complain_event_id'] = $data['order_id'];        // 投诉单号
                    /*
                    反馈类目ID
                    00:使用体验保障金退款；
                    02:通过其他方式退款;
                    03:已发货;
                    04:其他;
                    05:已完成售后服务;
                    06:非我方责任范围；
                    */
                    $arr['feedback_code'] = '02';                         // 支付宝侧投诉单号
                    $arr['feedback_content'] = $data['remark'];           // 反馈内容

                    $aop = new \AopClient();
                    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                    $aop->appId = $pay_config['app_id'];
                    $aop->rsaPrivateKey = $pay_config['key'];
                    $aop->alipayrsaPublicKey = $pay_config['other_public_key'];
                    $aop->apiVersion = '1.0';
                    $aop->signType = 'RSA2';
                    $aop->postCharset = 'utf-8';
                    $aop->format = 'json';

                    // 查询交易投诉列表
                    $request = new \AlipayMerchantTradecomplainFeedbackSubmitRequest();
                    $request->setComplainEventId($arr['complain_event_id']);
                    $request->setFeedbackCode($arr['feedback_code']);
                    $request->setFeedbackContent($arr['feedback_content']);
                    //$request->setBizContent(json_encode($arr));
                    $result = $aop->execute($request);
                    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                    $resultCode = $result->$responseNode->code;
                    if (!empty($resultCode) && $resultCode == 10000) {
                        $datas['status'] = 1;
                    } else {
                        $datas['status'] = 0;
                    }
                    $datas['order_id'] = $data['order_id'];
                    $datas['type'] = 0;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = $resdata;
                    $datas['create_time'] = time();
                }
            }

            // 微信
            if ($data['class'] == 1) {
                // 回复用户
                if ($data['type'] == 0) {

                    //$arr['complaint_id'] = $data['order_id'];                      // 投诉单号
                    $arr['complainted_mchid'] = $pay_config['merchant_id'];        // 被诉商户号
                    $arr['response_content'] = $data['remark'];                    // 回复内容

                    $url_path = $data['order_id'];
                    $url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/{$url_path}/response";

                    $mchid = $pay_config['merchant_id'];
                    $serial_no = $pay_config['other_public_key'];
                    $key = $pay_config['other_three'];
                    $temp = chunk_split($key, 64, "\n");
                    $key = "-----BEGIN PRIVATE KEY-----\n$temp-----END PRIVATE KEY-----\n";
                    $mch_private_key = openssl_get_privatekey($key);
                    $timestamp = time();
                    $nonce = md5($timestamp);
                    $http_method = 'POST';
                    $body = json_encode($arr);

                    $url_parts = parse_url($url);
                    $canonical_url = $url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : "");
                    $message = $http_method . "\n" .
                        $canonical_url . "\n" .
                        $timestamp . "\n" .
                        $nonce . "\n" .
                        $body . "\n";

                    openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
                    $sign = base64_encode($raw_sign);

                    $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $serial_no, $sign);

                    $header = [
                        'Accept: application/json',
                        'User-Agent: */*',
                        'Content-Type: application/json; charset=utf-8',
                        'Authorization: ' . $token,
                    ];

                    /*
                    PENDING：待处理
                    PROCESSING：处理中
                    PROCESSED：已处理完成
                    */

                    $resdata = go_curl($url, $body, 'post', $pay_config['wait_second'], $header);
                    if (!empty($resdata)) {
                        $datas['status'] = 0;
                    } else {
                        $datas['status'] = 1;
                    }
                    $datas['order_id'] = $data['order_id'];
                    $datas['type'] = 0;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = $resdata;
                    $datas['create_time'] = time();
                }

                // 处理完成
                if ($data['type'] == 1) {

                    //$arr['complaint_id'] = $data['order_id'];                      // 投诉单号
                    $arr['complainted_mchid'] = $pay_config['merchant_id'];        // 被诉商户号

                    $url_path = $data['order_id'];
                    $url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/{$url_path}/complete";

                    $mchid = $pay_config['merchant_id'];
                    $serial_no = $pay_config['other_public_key'];
                    $key = $pay_config['other_three'];
                    $temp = chunk_split($key, 64, "\n");
                    $key = "-----BEGIN PRIVATE KEY-----\n$temp-----END PRIVATE KEY-----\n";
                    $mch_private_key = openssl_get_privatekey($key);
                    $timestamp = time();
                    $nonce = md5($timestamp);
                    $http_method = 'POST';
                    $body = json_encode($arr);

                    $url_parts = parse_url($url);
                    $canonical_url = $url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : "");
                    $message = $http_method . "\n" .
                        $canonical_url . "\n" .
                        $timestamp . "\n" .
                        $nonce . "\n" .
                        $body . "\n";

                    openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
                    $sign = base64_encode($raw_sign);

                    $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"', $mchid, $nonce, $timestamp, $serial_no, $sign);

                    $header = [
                        'Accept: application/json',
                        'User-Agent: */*',
                        'Content-Type: application/json; charset=utf-8',
                        'Authorization: ' . $token,
                    ];

                    /*
                    PENDING：待处理
                    PROCESSING：处理中
                    PROCESSED：已处理完成
                    */

                    $resdata = go_curl($url, $body, 'post', $pay_config['wait_second'], $header);
                    if (!empty($resdata)) {
                        $datas['status'] = 0;
                    } else {
                        $datas['status'] = 1;
                    }
                    $datas['order_id'] = $data['order_id'];
                    $datas['type'] = 1;
                    $datas['child_company_name'] = $pay_config['name'];
                    $datas['child_company_title'] = $pay_config['title'];
                    $datas['create_param'] = json_encode($data);
                    $datas['return_param'] = $resdata;
                    $datas['create_time'] = time();
                }
            }

            if (ComplainModel::create($datas)) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }

        // 支付公司    
        $payment_company = PaymentPayCompanyModel::where(['status' => 1])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $items = [
            ['radio', 'class', '方式', '', ['支付宝', '微信'], 1],
            ['radio', 'type', '类型', '', ['回复用户', '处理完成'], 1],
            ['select', 'child_company', '支付公司', '', $payment_company],
            ['text', 'order_id', '投诉订单号'],
            ['text', 'remark', '备注'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('投诉') // 设置页面标题
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 导出数据
     * @return mixed
     */
    public function export($map = '')
    {
        ini_set('memory_limit', '1024M');
        ob_end_clean();

        if (!is_dir($this->file_path)) {
            $this->error('数据导出目录不存在！', url('index'));
        }
        set_time_limit(3600);

        if (!empty($map)) {
            $map = htmlspecialchars_decode($map);
            $map = urldecode($map);
            $map = str_replace("+", " ", $map);
            // 获取查询条件
            $map = json_decode($map, true);
        }

        $count = ComplainModel::where($map)->count();
        if (empty($count)) {
            $this->error('数据导出为空！', url('index'));
        }

        // 最多导出数量
        $export_order_max_count = pay_config('export_order_max_count');
        if ($count > $export_order_max_count) {
            $this->error("系统设置一次最多导出{$export_order_max_count}条数据！");
        }

        $date = date('Y-m-d');
        // 商户每天最多导出订单次数
        $order_export_day_count = pay_config('order_export_day_count');
        $order_map[] = ['merchant_id', '=', $this->merchant_id];
        $order_map[] = ['create_time', 'between time', ["$date 00:00:00", "$date 23:59:59"]];
        $download_count = DownloadModel::where($order_map)->count();
        if ($download_count >= $order_export_day_count) {
            $this->error("系统设置商户每天最多导出订单次数是{$order_export_day_count}次");
        }

        $download['id'] = date('YmdHis') . rand(100000, 999999);
        $download['merchant_id'] = $this->merchant_id;
        $download['title'] = "投诉列表导出条数（{$count}）";
        $download['file_name'] = $download['id'] . '.csv';
        $download['url'] = Request::module() . '/' . Request::controller() . '/' . Request::action();
        $download['status'] = 2;
        $download['programmer_remark'] = json_encode($map);
        $download_insert = DownloadModel::create($download);
        if (!$download_insert) {
            $this->error("导出失败");
        }

        $field = [
            'id',
            'order_id',
            'type',
            'create_param',
            'return_param',
            'create_time',
        ];

        $cellName = [
            '序号',
            '订单号',
            '类型',
            '创建参数',
            '返回参数',
            '创建时间',
        ];
        $fp = fopen($download['file_name'], 'w');

        foreach ($cellName as $key => $value) {
            $cellName[$key] = mb_convert_encoding($cellName[$key], 'gb2312', 'utf-8');
        }

        fputcsv($fp, $cellName);

        Db::name('payment_complain')
            ->where($map)
            ->field($field)
            ->chunk(200, function ($all) use ($fp) {
                foreach ($all as $single) {

                    $single['create_time'] = date('Y-m-d H:i:s', $single['create_time']);

                    $single['type'] = $single['type'] ? '列表' : '订单号';

                    $single['return_param'] = format_nice($single['return_param']);

                    foreach ($single as $key => $value) {
                        if (!in_array($key, ['cash', 'merchant_id'])) {
                            $single[$key] = "\t" . mb_convert_encoding($value, 'gb2312', 'utf-8');
                        }
                    }

                    fputcsv($fp, $single);
                    unset($single);
                }
            }, 'create_time', 'desc');
        fclose($fp);

        DownloadModel::update(['id' => $download['id'], 'status' => 1, 'update_time' => time()]);
        rename(Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . $download['file_name'], $this->file_path . $download['file_name']); // 移动到新目录

        $this->success('导出成功', url('download/index'));
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 获取数据
        $info = ComplainModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }
        $info['create_param'] = $info['create_param'] ? format_nice($info['create_param']) : '';
        $info['return_param'] = $info['return_param'] ? format_nice($info['return_param']) : '';

        $items = [
            ['static', 'id', 'ID'],
            ['radio', 'type', '类型', '', ['投诉列表', '投诉订单号']],
            ['textarea', 'create_param', '创建参数', '', '', '', ''],
            ['textarea', 'return_param', '返回参数', '', '', '', ''],
            ['static', 'order_id', '平台订单号'],
            ['radio', 'status', '状态', '', ['失败', '成功']],
            ['datetime', 'create_time', '订单创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }
}
